/*
File Description: creates a new mysql connection.
*/

//Standard mysql libraries and configurations.
/*var Client = require('mysql').Client
	,USER = ''
	,PASS = ''
	,DATABASE = '';*/

//Create a *single* mysql connection.
exports.newMySQLConnection = function(){
	//return null; //delete me.
	var Client = require('mysql').Client

	var mysql = new Client();
	
	mysql.user = 'root';
	mysql.password = '';
	mysql.host='127.0.01';
	mysql.database='chatservice';
	
	//mysql.connect();
	
	return mysql;
}

//Functions MYSQL
exports.loadMethods = function(mysql){
	Object.append(mysql,{
		conectNickA: function(idchat){
			var res = this.noConectedAnon(idchat);
			nAnon = res.length;
			
			if(nAnon > 0){
				var d = new Date();
				var time = d.getTime();
				this.query(
				'INSERT INTO `nick` n (idchat, registered, lastLogin, nick, connected, anon) VALUES('+idchat+','+time+','+time+',"anon'+(nAnon+1)+'",1,1)',
        		function cb(err, results, fields) {
		       		if (err) {
		            	console.log("Error: " + err.message);
		            	throw err;
		        	}
        		});
        		nickA = "anon"+(nAnon+1);
			}else{
				nickA = res[0].nick;
				this.query(
				'UPDATE nick n SET n.connected = 1 WHERE n.nick LIKE '+nickA+' AND n.idchat = '+idchat,
        		function cb(err, results, fields) {
		       		if (err) {
		            	console.log("Error: " + err.message);
		            	throw err;
		        	}
        		});
			}
			return nickA;
		},
		noConectedAnon: function(idchat){
			var res = {};
			this.query(
				'SELECT * AS cont FROM `nick` n WHERE n.anon = 1 AND n.connected = 0 AND n.idchat = '+idchat,
        		function cb(err, results, fields) {
		       		if (err) {
		            	console.log("Error: " + err.message);
		            	throw err;
		        	}
		        	res = results;
        	});
        	return res;
		}	
	});
}
